<?php


namespace app\index\model;


use think\Db;

class Token
{


    private static $RedisKeyRefreshTime = 1800; //Token Redis 刷新时间  半小时1800秒

    private static $strRandLen = 36; //随机生成的key值长度


    /**
     * 随机字符串
     * @param int $len 长度
     * @return string
     */
    function randStr(int $len)
    {
        $chars  = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // characters to build the password from
        $string = "";
        for ($i = $len; $i > 0; $i--) {
            $position = rand() % strlen($chars);
            $string   .= substr($chars, $position, 1);
        }

        return $string;
    }

    //生成新的token
    public function NewToken(array $info)
    {

        if (empty($info)) {
            return [];
        }

        $secretKey = $this->randStr(self::$strRandLen);

        $token     = FKencrypt::getInstance()->Encrypt(json_encode($info), $secretKey);

        //存入缓存和数据库
        Db::table("user_token")->insert([
            'token' =>$token,
            'key' => $secretKey,
            'user_id' => $info['user_id'],
            'create_time' => date("Y-m-d H:i:s",time()),
            'update_time' => date("Y-m-d H:i:s",time()),
        ]);
        return [$token, $secretKey];
    }

    //解密token
    public static function decryptToken($token)
    {

        if (empty($token)) {
            return false;
        }

        $data = Db::table('user_token')->where(['token' => $token])->find();

        if (empty($data) || empty($data['key'])) {
            return false;
        }

        $userInfo = FKencrypt::getInstance()->Decrypt($token, $data['key']);

        if (empty($userInfo)) {
            return false;
        }
        return $userInfo;
    }





}